package com.ahmedmisbah.andgenplus.utils.json.generator;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.ahmedmisbah.andgenplus.utils.json.exceptions.Json2PojoGeneratorException;
import com.googlecode.jsonschema2pojo.GenerationConfig;
import com.googlecode.jsonschema2pojo.NoopAnnotator;
import com.googlecode.jsonschema2pojo.SchemaGenerator;
import com.googlecode.jsonschema2pojo.SchemaMapper;
import com.googlecode.jsonschema2pojo.SchemaStore;
import com.googlecode.jsonschema2pojo.rules.RuleFactory;
import com.sun.codemodel.JCodeModel;

public class Json2PojoGenerator {

	public static void generatePojoFromJson(String jsonFilePath,
			String projectPath, String className, String packageName)
			throws Json2PojoGeneratorException {
		JCodeModel codeModel = new JCodeModel();

		URL source;

		try {
			source = new File(jsonFilePath).toURI().toURL();
		} catch (MalformedURLException e) {
			throw new Json2PojoGeneratorException(e);
		}

		GenerationConfig config = new Json2PojoGenerationConfig();

		RuleFactory ruleFactory = new RuleFactory(config, new NoopAnnotator(),
				new SchemaStore());

		SchemaGenerator generator = new SchemaGenerator();

		SchemaMapper mapper = new SchemaMapper(ruleFactory, generator);

		try {
			mapper.generate(codeModel, className, packageName, source);
		} catch (IOException e) {
			throw new Json2PojoGeneratorException(e);
		}

		try {
			codeModel.build(new File(projectPath));
		} catch (IOException e) {
			throw new Json2PojoGeneratorException(e);
		}
	}

	public static void main(String args[]) throws Exception {
		Json2PojoGenerator.generatePojoFromJson("D://booklist.json",
				"d://test", "Test", "com.ahmedmisbah");
	}

}
